/**
 * @Author : SL
 * @Date : 2019/5/30
 * @Version :1.0
 * @Last Modified by : SL
 * @Last Modified time : 2019/5/30
 **/
const {exec} = require('../db/mysql')
const getList = (author, keyword) => {
    let sql = `select * from blogs where 1=1 `
    if (author) {
        sql += `and author='${author}' `
    }
    if (keyword) {
        sql += `and title like '%${keyword}%' `
    }
    sql += `order by createtime desc; `
    //返回的是promise
    return exec(sql)
}

const getDetail = (id) => {
    //先返回假数据（格式是正确的）
    // return [
    //     {
    //         id: 1,
    //         title: "标题1",
    //         content: "内容1",
    //         createTime: 1559182437339,
    //         author: "zhangsan"
    //     }
    // ]
    const sql = `select * from blogs where id='${id}'`
    return exec(sql).then(rows => {
        return rows[0]
    })
}

const newBlog = (blogData = {}) => {
    //blogData 是一个博客对象，包含title content 属性
    // console.log("blogData：",blogData)
    // return{
    //     id:3    //表示新建博客，插入到数据表里面的ID
    // }
    const title = blogData.title
    const content = blogData.content
    const author = blogData.author
    const createTime = Date.now()

    const sql = `insert into blogs(title,content,createtime,author)
                values('${title}','${content}',${createTime},'${author}');`
    return exec(sql).then(insertData => {
        // console.log('inserData is', insertData)
        return {
            id: insertData.insertId
        }
    })
}

const updateBlog = (id, blogData = {}) => {
    const title = blogData.title
    const content = blogData.content

    const sql = `
         update blogs set title='${title}',content='${content}' where id='${id}';
    `
    return exec(sql).then(updateData => {
        // console.log('updateData is', updateData)
        if (updateData.affectedRows > 0) {
            return true
        }
        return false
    })
    //id 要更新的博客id
    //blogData 是一个博客对象，包含title content 属性
    // console.log('update blog',id,blogData)
    // return true
}

const delBlog = (id, author) => {
    //id 要删除的博客id
    // return true
    const sql = `delete from blogs where id='${id}'and author='${author}'`
    return exec(sql).then(delData => {
        // console.log('delData is', delData)
        if (delData.affectedRows > 0) {
            return true
        }
        return false
    })
}
module.exports = {
    getList,
    getDetail,
    newBlog,
    updateBlog,
    delBlog
}